package com.gjd.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjd.config.AlipayConfig;
import com.gjd.domain.ResponseResult;
import com.gjd.domain.entity.Orders;
import com.gjd.domain.entity.PayRecord;
import com.gjd.domain.entity.PayStatus;
import com.gjd.domain.vo.PayRecordVo;
import com.gjd.mapper.OrdersMapper;
import com.gjd.mapper.PayRecordMapper;
import com.gjd.service.PayService;
import com.gjd.mapper.PayMapper;
import com.gjd.utils.BeanCopyUtils;
import com.gjd.utils.IdWorkerUtils;
import com.gjd.utils.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author yang'shun'tao
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2023-01-16 11:42:21
 */
@Service
@Slf4j
public class PayServiceImpl extends ServiceImpl<PayMapper, Orders>
        implements PayService {

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private PayRecordMapper payRecordMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public ResponseResult operateOrders(Orders orders) {
        //创建订单 有则直接返回
        Orders corders = createOrder(orders);
        //添加支付记录
        PayRecord payRecord = createPayRecord(corders);
        payRecordMapper.insert(payRecord);
        //生成支付二维码
        String qrCode = null;
        try {
            //url要可以被模拟器访问到，url为下单接口(稍后定义)
            qrCode = new QRCodeUtil().createQRCode("http://localhost/order/requestPay?payNo=" + payRecord.getPayNo(), 200, 200);
        } catch (IOException e) {
            return null;
        }
        //封装要返回的数据
        PayRecordVo payRecordVo = BeanCopyUtils.copyBean(payRecord, PayRecordVo.class);
        payRecordVo.setQrcode(qrCode);
        return ResponseResult.okResult(payRecordVo);
    }

    @Override
    public PayRecord getPayRecordByPayNo(String payNo) {
        LambdaQueryWrapper<PayRecord> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(PayRecord::getPayNo,payNo);
        PayRecord payRecord = payRecordMapper.selectOne(queryWrapper);
        return payRecord;
    }
    @Transactional
    @Override
    public void saveAliPayStatus(PayStatus payStatus) {
        String tradeStatus = payStatus.getTradeStatus();
        String appId = payStatus.getAppId();
        if (tradeStatus.equals("TRADE_SUCCESS")){
            String payNo = payStatus.getOutTradeNo();
            PayRecord payRecord = getPayRecordByPayNo(payNo);
            if (payRecord == null){
                log.info("收到支付结果，但是查询不到支付记录");
            }
            Integer status = payRecord.getStatus();
            if (status == 602){
                log.info("收到支付结果，但是支付状态为已支付");
            }
            if (appId!= AlipayConfig.APPID){
                log.info("手支付结果，但是支付宝appid错误");
            }

            //校验结束
            //开始更新支付记录
            PayRecord nPayRecord = new PayRecord();
            nPayRecord.setStatus(602);
            nPayRecord.setOutPayNo(payStatus.getTradeNo());
            nPayRecord.setOutPayChannel(1);
            nPayRecord.setPaySucessTime(LocalDateTime.now());
            LambdaQueryWrapper<PayRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PayRecord::getPayNo,payNo);
            int res = payRecordMapper.update(payRecord, queryWrapper);
            if (res>0){
                log.info("更新支付记录成功");
            }else {
                log.info("更新支付记录失败");
            }

            //更新订单
            Long orderId = payRecord.getOrderId();
            Orders orders = ordersMapper.selectById(orderId);
            if (orders==null){
                log.info("收到支付通知，但是查询不到订单");
            }
            Orders nOrders = new Orders();
            nOrders.setStatus("已支付");
            LambdaQueryWrapper<Orders> nQueryWrapper = new LambdaQueryWrapper<>();
            nQueryWrapper.eq(Orders::getId,orderId);
            int nRes = ordersMapper.update(nOrders, nQueryWrapper);
            if (nRes>0){
                log.info("更新订单成功");
            }
            else {
                log.info("更新订单失败");
            }
        }
    }


    private PayRecord createPayRecord(Orders order) {
        PayRecord payRecord = new PayRecord();
        long payNo = IdWorkerUtils.getInstance().nextId();
        payRecord.setPayNo(payNo);
        payRecord.setOrderId(order.getId());
        payRecord.setStatus(601);
        payRecord.setCreateTime(LocalDateTime.now());
        payRecord.setServerId(order.getServerId());
        payRecord.setUserId(order.getUserId());
        payRecord.setTotalPrice(order.getTotalPrice());
        payRecord.setServeTime(order.getServerTime());
        //差paysucesstime
        return payRecord;
    }


    //创建订单
    private Orders createOrder(Orders orders) {
        //检查是否已有订单
        if (orders.getId() != null) {
            return orders;
        }
        //没有则创建新订单
        Orders norder = BeanCopyUtils.copyBean(orders, Orders.class);
        norder.setStatus("未支付");
        payMapper.insert(norder);
        return norder;
    }
}




